//
//  OrderViewController.swift
//  PutaoMaternityMatron
//
//  Created by xianzhiliao on 2017/3/21.
//  Copyright © 2017年 Putao. All rights reserved.
//

import UIKit

class OrderViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet var vScroll: UIScrollView!
    @IBOutlet var btnSubmit: UIButton!
    @IBOutlet var tfName: UITextField!
    @IBOutlet var tfPhone: UITextField!
    @IBOutlet var cLineHeight: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "请填写信息"
        btnSubmit.layer.cornerRadius = 2
        cLineHeight.constant = 1 / UIScreen.main.scale
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func actionSubmit(_ sender: Any) {
        let name = self.tfName.text!
        let phone = self.tfPhone.text!
        let urlString = (HttpEnv.host as String) + "/order/matron_user_info?user_name='\(name)'&user_mobile='\(phone)'"
        
        // url编码否则有中文时报错
        let encodeURl = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        
        var request = URLRequest(url: (URL(string:encodeURl!)! as URL))
        request.httpMethod = "GET"
        let dataTask = URLSession.shared.dataTask(with: request,
                        completionHandler: {(data, response, error) -> Void in
                            if error != nil{
                                return
                            }else{
                                do {
                                    let json: Any = try! JSONSerialization.jsonObject(with: data!, options: [])
                                    let jsonDic = json as! [String: AnyObject]
                                    let code = jsonDic["code"] as!NSInteger
                                    if (code == 0){
                                        
                                    }else{
                                        if(code == 123456){
                                            print(jsonDic["msg"] ?? "相同手机号码不能重复提交")
                                        }
                                    }
                                }
                            }
        }) as URLSessionTask
        
        dataTask.resume()
    }

    @IBAction func actionTap(_ sender: Any) {
        self.vScroll.setContentOffset(CGPoint.zero, animated: true)
        self.vScroll.layoutIfNeeded()
        self.view.endEditing(true)
    }
    func textFieldDidBeginEditing(_ textField: UITextField){
        self.vScroll.setContentOffset(CGPoint(x:0,y:textField.frame.origin.y - 20), animated: true)
    }
    func textFieldDidEndEditing(_ textField: UITextField){
        self.vScroll.contentOffset = CGPoint(x:0,y:0)
        self.vScroll.setContentOffset(CGPoint.zero, animated: true)
    }
}
